package servlets;

import java.io.IOException;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestHandler;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import clases.Response;
import constantes.Constantes;
import services.EventoServiceIntf;

@Component("eventos")
public class Eventos extends HttpServlet implements HttpRequestHandler{

	private static final long serialVersionUID = 1L;

	@Autowired
	private EventoServiceIntf eventoService;

	private Integer operacion;
	private Long ultimo;
	private String tipo;

	public void handleRequest(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		System.out.println("EVENTOS");

		@SuppressWarnings("unchecked")
		Enumeration<String> parametros = arg0.getParameterNames();

		while (parametros.hasMoreElements()) {
			String parametro= (String) parametros.nextElement();
			switch(parametro){
			case Constantes.TAG_OPERACION:
				operacion = Integer.parseInt((String) arg0.getParameter(parametro));
				break;
			case Constantes.TAG_ULTIMO:
				ultimo = new Long((String) arg0.getParameter(parametro));
				break;
			case Constantes.TAG_TIPO:
				tipo =  (String)arg0.getParameter(parametro);
				break;

			default:
				break;

			}
		}

		ejecutaOperacion(arg1);

	}

	private void ejecutaOperacion(HttpServletResponse response) throws IOException {
		Gson gson = new Gson();
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		Response ok = new Response();
		
		switch(operacion){
			case 1://ALTA
				try{
					ok.setObject(gson.toJson(eventoService.getEventos(ultimo)));
					ok.setOk(true);
					ok.setComent(Constantes.COMENTARIO_VACIO);
					response.getWriter().write(gson.toJson(ok));
				}catch (Exception e) {
					ok.setOk(false);
					ok.setComent(e.getMessage());
					response.getWriter().write(gson.toJson(ok));
				}
				

			break;
		case 2://ACTUALIZACION
			try{
				response.getOutputStream().print("ok");
			}catch (Exception e) {
				response.getOutputStream().print("ko");
			}
			break;
		case 3://UNICO
			try{
				response.getOutputStream().print("ok");
			}catch (Exception e) {
				response.getOutputStream().print("ko");
			}
			break;
		default:
			break;
		}

	}


}
